package com.jay.io.clazz;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ReaderWriterSample {
	public static void main(String[] args) {
		try {
			File file = new File("out.txt");

			BufferedReader bufInputReader = new BufferedReader(new FileReader(
					file));

			// 将文件读入字符数组
			CharArrayWriter charArrayWriter = new CharArrayWriter();

			char[] array = new char[1];
			while (bufInputReader.read(array) != -1) {
				charArrayWriter.write(array);
			}

			charArrayWriter.close();
			bufInputReader.close();

			// 显示字符内容
			array = charArrayWriter.toCharArray();
			for (int i = 0; i < array.length; i++) {
				System.out.print(array[i] + " ");
			}
			System.out.println();

			// 让使用者输入位置与字符修改字符数组内容
			Scanner scanner = new Scanner(System.in);

			System.out.println("输入修改位置");
			int pos = scanner.nextInt();
			System.out.println("输入修改字符");
			char ch = scanner.next().charAt(0);
			array[pos - 1] = ch;

			// 将字符数组内容存回文件
			CharArrayReader charArrayReader = new CharArrayReader(array);

			BufferedWriter bufWriter = new BufferedWriter(new FileWriter(file));

			char[] tmp = new char[1];
			while (charArrayReader.read(tmp) != -1) {
				bufWriter.write(tmp);
			}

			charArrayReader.close();
			bufWriter.flush();
			bufWriter.close();
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("请指定文件名！");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
